package com.module.my.model

import android.text.TextUtils
import cn.leancloud.LCObject
import cn.leancloud.LCQuery
import com.module.app.base.BaseViewModel
import com.module.app.bean.ListViewBean
import com.module.app.ext.loginTopFlow
import com.module.base.ext.request
import com.module.base.utils.AppUtils
import com.module.base.utils.CommonUtils
import com.module.base.utils.ToastUtils
import com.module.frame.ext.postEvent
import com.module.my.R
import com.module.my.bean.IMyType
import com.module.my.bean.MyBean
import com.module.my.bus.PayBus
import com.module.third.learcloud.lcGetCurrentInstallation
import com.module.third.learcloud.lcQuerySingle
import com.module.third.learcloud.lcSave
import kotlinx.coroutines.flow.MutableSharedFlow
import java.util.*

class MyViewModel : BaseViewModel() {

    /**
     * 设置用户信息
     */
    val userDataFlow: MutableSharedFlow<Boolean> by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
        MutableSharedFlow()
    }

    /**
     * 绑定用户信息
     */
    val bindingFlow: MutableSharedFlow<com.module.app.bean.UserBean> by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
        MutableSharedFlow()
    }

    /**
     * 价格信息
     */
    val priceFow: MutableSharedFlow<PayBus> by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
        MutableSharedFlow()
    }

    fun getData() {
        val list: MutableList<MyBean> = ArrayList()
        list.add(MyBean("我的VIP", R.drawable.my_icon_vip, IMyType.IListType.vip))
        list.add(MyBean("问题解答", R.drawable.my_icon_wenti, IMyType.IListType.problem))
        list.add(MyBean("主题皮肤", R.drawable.my_icon_skin, IMyType.IListType.skin))
        if (com.module.app.bean.ConfigBean.getInstance().switchConfig.isPay) {
            list.add(MyBean("请我喝一杯奶茶", R.drawable.my_icon_naicha, IMyType.IListType.pay))
        }
        list.add(MyBean("绑定邀请码", R.drawable.my_icon_invite_code, IMyType.IListType.inviteCode))
        list.add(MyBean("邀请有礼", R.drawable.my_share_friends, IMyType.IListType.share))
        list.add(MyBean("意见反馈", R.drawable.my_icon_feedback, IMyType.IListType.feedback))
        if (!TextUtils.isEmpty(com.module.app.bean.ConfigBean.getInstance().qqGroupKey)) {
            list.add(MyBean("联系我们", "加群一起探讨", R.drawable.my_icon_kefu, IMyType.IListType.kefu))
        } else {
            list.add(MyBean("联系我们", R.drawable.my_icon_kefu, IMyType.IListType.kefu))
        }
        list.add(MyBean("五星好评", R.drawable.my_icon_evaluate, IMyType.IListType.evaluate))
        if (com.module.app.bean.ConfigBean.getInstance().isUpdate) {
            list.add(MyBean("有新版本", R.drawable.my_icon_new, IMyType.IListType.New))
        }
        list.add(MyBean("设置", R.drawable.my_icon_set, IMyType.IListType.set))
        postEvent(listFlow, ListViewBean(true, list, true))
    }

    fun getPay(price: String, text: String) {
        request({
            val tClass: Class<com.module.app.bean.PayBean> = com.module.app.bean.PayBean::class.java
            val query = LCQuery<LCObject>(tClass.simpleName)
            lcQuerySingle(query, tClass)
        }, {
            check(it != null) {
                "获取支付信息失败"
            }
            postEvent(priceFow, PayBus(it, price, text))
        }, {
            ToastUtils.showShort("获取支付信息失败")
        }, true)
    }

    fun getUser() {
        if (TextUtils.isEmpty(com.module.app.utils.UserUtils.getUserId())) {
            postEvent(userDataFlow, true)
            getPush()
            return
        }
        request({
            val tClass = com.module.app.bean.UserBean::class.java
            val query = LCQuery<LCObject>(tClass.simpleName)
            query.whereEqualTo("objectId", com.module.app.utils.UserUtils.getUserId())
            lcQuerySingle(query, tClass)
        }, {
            it?.let {
                com.module.app.utils.UserUtils.setUserBean(it)
                postEvent(userDataFlow, true)
                //获取推送消息
                getPush()
                //设备id不相同
                if (it.deviceId != AppUtils.getAndroidId()) {
                    postEvent(loginTopFlow, true)
                }
            }
        }, {}, false)
    }

    private fun getPush() {
        request({
            lcGetCurrentInstallation()
        }, { pushId ->
            check(!pushId.isNullOrEmpty()) {
                CommonUtils.getString(R.string.error_unknow)
            }
            //有登录的话，要保存pushId
            if (!com.module.app.utils.UserUtils.isLogin()) {
                return@request
            }
            //如果pushId跟用户信息不匹配，则更新
            if (pushId != com.module.app.utils.UserUtils.getPushId()) {
                val userBean = com.module.app.utils.UserUtils.getUserBean()
                userBean.pushId = pushId
                saveUser(userBean)
            }
        }, {}, false)
    }

    private fun saveUser(userBean: com.module.app.bean.UserBean) {
        request({
            lcSave(userBean, userBean.objectId, com.module.app.bean.UserBean::class.java)
        }, {
            check(it != null) {
                CommonUtils.getString(R.string.error_unknow)
            }
            com.module.app.utils.UserUtils.setUserBean(it)
        }, {}, false)
    }

    /**
     * 绑定用户
     */
    fun getBindingUser(userId: String) {
        request({
            val tClass = com.module.app.bean.UserBean::class.java
            val query = LCQuery<LCObject>(tClass.simpleName)
            query.whereEqualTo("objectId", userId)
            lcQuerySingle(query, tClass)
        }, {
            check(it != null) {
                "没有找到该用户"
            }
            postEvent(bindingFlow, it)
        }, {
            ToastUtils.showShort(it.msg)
        }, true)
    }
}